<?php

function _cfg($key){
	
}

function yunma($ma,$html="span"){
	$list=explode(",",$ma);
	$st="";
	foreach($list as $list2){
		$st.="<".$html.">".$list2."</".$html.">";
	}
	return $st;
}

//判断商品是否揭晓
function get_shop_if_jiexiao($shopid=null){
	$db = new \Think\Model();
	$record=$db->query("select * from `__PREFIX__shoplist` where `id`='$shopid' LIMIT 1");
	if(empty($record)) return false;
	$record = current($record);
	if($record['q_user']){
		$record['q_user'] = unserialize($record['q_user']);
		return $record;
	}else{
		return $record;
	}
}

//
function microt($time,$x=null){
	$len=strlen($time);
	if($len<13){
		$time=$time."0";
	}
	$list=explode(".",$time);
	if($x=="L"){
		return date("His",$list[0]).substr($list[1],0,3);
	}else if($x=="Y"){
		return date("Y-m-d",$list[0]);
	}else if($x=="H"){
		return date("H:i:s",$list[0]).".".substr($list[1],0,3);
	}else if($x=="r"){
		return date("Y年m月d日 H:i",$list[0]);
	}else{
		return date("Y-m-d H:i:s",$list[0]).".".substr($list[1],0,3);
	}
}

/*字符过滤url*/
function safe_replace($string) {
	$string = str_replace('%20','',$string);
	$string = str_replace('%27','',$string);
	$string = str_replace('%2527','',$string);
	$string = str_replace('*','',$string);
	$string = str_replace('"','&quot;',$string);
	$string = str_replace("'",'',$string);
	$string = str_replace('"','',$string);
	$string = str_replace(';','',$string);
	$string = str_replace('<','&lt;',$string);
	$string = str_replace('>','&gt;',$string);
	$string = str_replace("{",'',$string);
	$string = str_replace('}','',$string);
	$string = str_replace('\\','',$string);
	return $string;
}

/*过滤搜索关键词*/
function search_replace($string) {
	$string = str_replace('%20','',$string);
	$string = str_replace('%27','',$string);
	$string = str_replace('%2527','',$string);
	$string = str_replace('*','',$string);
	$string = str_replace('"','',$string);
	$string = str_replace("'",'',$string);
	$string = str_replace('"','',$string);
	$string = str_replace(';','',$string);
	$string = str_replace('<','',$string);
	$string = str_replace('>','',$string);
	$string = str_replace("{",'',$string);
	$string = str_replace('}','',$string);
	$string = str_replace('\\','',$string);
	$string = str_replace('\\\\','',$string);
	$string = str_replace('/','',$string);
	$string = str_replace('//','',$string);
	return $string;
}


function get_ip($id,$ipmac=null){
	$record=M('member_go_record')->where(array('id' => $id))->find();
	$ip=explode(',',$record['ip']);
	if($ipmac=='ipmac'){
		return $ip[1];
	}elseif($ipmac=='ipcity'){
		return $ip[0];
	}
}

/**
 * 获取用户昵称
* uid 用户id，或者 用户数组
* type 获取的类型, userName,userEmail,userPhone
* key  获取完整用户名, sub 截取,all 完整
*/
function get_user_name($uid='',$type='userName',$key='sub'){
	if(is_array($uid)){
		if(isset($uid['userName']) && !empty($uid['userName'])){
			return $uid['userName'];
		}
		if(isset($uid['userEmail']) && !empty($uid['userEmail'])){
			if($key=='sub'){
				$email = explode('@',$uid['userEmail']);
				return $uid['userEmail'] = substr($uid['userEmail'],0,2).'*'.$email[1];
			}else{
				return $uid['userEmail'];
			}
		}
		if(isset($uid['userPhone']) && !empty($uid['userPhone'])){
			if($key=='sub'){
				return $uid['userPhone'] = substr($uid['userPhone'],0,3).'****'.substr($uid['userPhone'],7,4);
			}else{
				return $uid['userPhone'];
			}
		}
		return '';
	}else{
		$uid = intval($uid);
		$info = M('Users')->where(array('userId' => $uid))->field(array('userName','userEmail','userPhone'))->find();
		if(isset($info['userName']) && !empty($info['userName'])){
			return $info['userName'];
		}

		if(isset($info['userEmail']) && !empty($info['userEmail'])){
			if($key=='sub'){
				$email = explode('@',$info['userEmail']);
				return $info['userEmail'] = substr($info['userEmail'],0,2).'*'.$email[1];
			}else{
				return $info['userEmail'];
			}
		}
		if(isset($info['userPhone']) && !empty($info['userPhone'])){
			if($key=='sub'){
				return $info['userPhone'] = substr($info['userPhone'],0,3).'****'.substr($info['userPhone'],7,4);
			}else{
				return $info['userPhone'];
			}
		}
		if(isset($info[$type]) && !empty($info[$type])){
			return $info[$type];
		}
		return null;
	}
}

/*
 * 获取用户信息
*/
function get_user_key($uid='',$type='img',$size=''){

	if(empty($uid) && $type == 'img'){
		return 'Upload/member.jpg';
	}

	if(is_array($uid)){
		if(isset($uid[$type])){
			if($type=='img'){
				$fk = explode('.',$uid[$type]);
				$h = array_pop($fk);
				if($size){
					return $uid['userPhoto'].'_'.$size.'.'.$h;
				}else{
					return $uid['userPhoto']?$uid['userPhoto']:'Upload/member.jpg';
				}
			}
			return $uid['userPhoto']?$uid['userPhoto']:'Upload/member.jpg';
		}
		return 'null';
	}else{
		$uid = intval($uid);
		$info = M('users')->where(array('userId' => $uid))->find();
		if($type=='img'){
			$fk = explode('.',$info['userPhoto']);
			$h = array_pop($fk);
			if($size){
				return $info['userPhoto'].'_'.$size.'.'.$h;
			}else{
				return $info['userPhoto']?$info['userPhoto']:'Upload/member.jpg';
			}
		}
		if(isset($info[$type])){
			return $info[$type];
		}
		return null;
	}
}

/**
 *   生成购买的抢购码
*	user_num 		@生成个数	如果购买1个，生成一个抢购码
*	shopinfo		@商品信息	商品订单信息
*	ret_data		@返回信息
*/
function pay_get_shop_codes($user_num=1,$shopinfo=null,&$ret_data=null){
	$db = new \Think\Model();
	$ret_data['query'] = true;
	$table = $shopinfo['codes_table'];
	$codes_arr = array();
	//取出最后一条
	$codes_one = $db->query("select id,s_id,s_cid,s_len,s_codes from `__PREFIX__$table` where `s_id` = '$shopinfo[id]' order by `s_cid` DESC  LIMIT 1 for update");
	$codes_one = current($codes_one);
	$codes_arr[$codes_one['s_cid']] = $codes_one;
	$codes_count_len = $codes_arr[$codes_one['s_cid']]['s_len'];
	//如果剩余抢购码长 小于 购物长度
	if($codes_count_len < $user_num && $codes_one['s_cid'] > 1){
		for($i=$codes_one['s_cid']-1;$i>=1;$i--){
			$ab = $db->query("select id,s_id,s_cid,s_len,s_codes from `__PREFIX__$table` where `s_id` = '$shopinfo[id]' and `s_cid` = '$i'  LIMIT 1 for update");
			$codes_arr[$i] = current($ab);
			$codes_count_len += $codes_arr[$i]['s_len'];
			if($codes_count_len > $user_num)  break;
		}
	}

	if($codes_count_len < $user_num) $user_num = $codes_count_len;

	$ret_data['user_code'] = '';
	$ret_data['user_code_len'] = 0;

	foreach($codes_arr as $icodes){
		$u_num = $user_num;
		$icodes['s_codes'] = unserialize($icodes['s_codes']);
		$code_tmp_arr = array_slice($icodes['s_codes'],0,$u_num);
		$ret_data['user_code'] .= implode(',',$code_tmp_arr);
		$code_tmp_arr_len = count($code_tmp_arr);

		if($code_tmp_arr_len < $u_num){
			$ret_data['user_code'] .= ',';
		}

		$icodes['s_codes'] = array_slice($icodes['s_codes'],$u_num,count($icodes['s_codes']));
		$icode_sub = count($icodes['s_codes']);
		$icodes['s_codes'] = serialize($icodes['s_codes']);

		if(!$icode_sub){
			$query = $db->execute("UPDATE `__PREFIX__$table` SET `s_cid` = '0',`s_codes` = '$icodes[s_codes]',`s_len` = '$icode_sub' where `id` = '$icodes[id]'");
			if(!$query)$ret_data['query'] = false;
		}else{
			$query = $db->execute("UPDATE `__PREFIX__$table` SET `s_codes` = '$icodes[s_codes]',`s_len` = '$icode_sub' where `id` = '$icodes[id]'");
			if(!$query)$ret_data['query'] = false;
		}
		$ret_data['user_code_len'] += $code_tmp_arr_len;
		$user_num  = $user_num - $code_tmp_arr_len;
	}

}

//生成订单号  100000000
function pay_get_dingdan_code($dingdanzhui=''){
	return $dingdanzhui.time().substr(microtime(),2,6).rand(0,9);
}


/**
 * https请求（支持GET和POST）
 * @param $url
 * @param string $data
 * @return mixed
 */
function https_request($url, $data = null){
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
	//如果$data不是空使用POST
	if (!empty($data)){
		curl_setopt($curl, CURLOPT_POST, 1);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
	}
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	$output = curl_exec($curl);
	curl_close($curl);
	return $output;
}
/**
 * 获取时时彩开奖号码
 * @return int | number
 */
function autumn_getcode(){
	$url = 'http://f.apiplus.cn/cqssc-1.json';
	$json = https_request($url);
	$result = json_decode($json,true);
	if (!empty($result['data'][0])){
		$openCode = null;
		$data = current($result['data']);
		$ex = explode(',', $data['opencode']);
		foreach ($ex as $key => $value){
			$openCode .= $value;
		}
		if (!$openCode){
			$openCode = '00000';
		}
		return array('opentime' => $data['expect'],'opencode' => $openCode);
	}else{
		return false;
	}
}

/* 获取ip + 地址*/
function _get_ip_dizhi($ip=null){
	$opts = array(
			'http'=>array(
					'method'=>"GET",
					'timeout'=>5,)
	);
	$context = stream_context_create($opts);
	if($ip){
		$ipmac = $ip;
	}else{
		//$ipmac=_get_ip();
		$ipmac=get_client_ip();
		if(strpos($ipmac,"127.0.0.") === true)return '';
	}

	$url_ip='http://ip.taobao.com/service/getIpInfo.php?ip='.$ipmac;
	$str = @file_get_contents($url_ip, false, $context);
	if(!$str) return "";
	$json=json_decode($str,true);
	if($json['code']==0){

		$json['data']['region'] = addslashes(_htmtocode($json['data']['region']));
		$json['data']['city'] = addslashes(_htmtocode($json['data']['city']));

		$ipcity= $json['data']['region'].$json['data']['city'];
		$ip= $ipcity.','.$ipmac;
	}else{
		$ip="";
	}
	return $ip;
}

/**
 揭晓与插入商品
@shop   商品数据
*/
function pay_insert_shop($shop='',$type=''){
	$time=sprintf("%.3f",microtime(true)+(int)C('GOODS_END_TIME'));
	$db = new \Think\Model();
	if(!empty($shop['xsjx_time'])){
		return $db->query("UPDATE `__PREFIX__shoplist` SET `canyurenshu`=`zongrenshu`,	`shenyurenshu` = '0' where `id` = '$shop[id]'");
	}
	if ($shop['q_uid']){
		return false;
	}
	//时时彩开奖码
	$time_time_data = autumn_getcode();
	if (!is_array($time_time_data)){
		$time_time_data = array('opentime' => '','opencode' => '00000');
	}

	$tocode = new \Go\Util\tocode();
	$tocode->shop = $shop;
	$tocode->shishi_cai = $time_time_data;
	$tocode->run_tocode($time,100,$shop['canyurenshu'],$shop);

	$code = $tocode->go_code;
	$counttime = $tocode->count_time;
	$content = addslashes($tocode->go_content);
	//作弊
	if($shop['q_uid_a']){
		$ex_info=$db->query("select * from `__PREFIX__member_go_record` where `shopid` = '$shop[id]' and `shopqishu` = '$shop[qishu]' and `uid`='{$shop['q_uid_a']}'");
		$ex_info = current($ex_info);
		$ex_code=explode(",",$ex_info['goucode']);
		$ex_count=count($ex_code);
		$ex_rand=rand(0,$ex_count-1);
		if($ex_code[$ex_rand]){
			$chazhi=$ex_code[$ex_rand]-$code;
			if($chazhi>0)$counttime=$counttime+$chazhi;
			else $counttime=$counttime-abs($chazhi);
			$code=$ex_code[$ex_rand];
				
			//添加时间校准
			if(!empty($chazhi)){
				$last_info=$db->query("select * from `__PREFIX__member_go_record` where `shopid` = '$shop[id]' and `shopqishu` = '$shop[qishu]' order by id desc limit 1");
				$last_info = current($last_info);
				$time_t_str = str_replace('.','',$last_info['time']);
				$time_str = bcadd($time_t_str,$chazhi);
				$time_arr = str_split($time_str,10);
				$str_t_time = $time_arr[0].'.'.$time_arr[1];
				$db->execute("UPDATE `__PREFIX__member_go_record` SET `time`='$str_t_time' where `id` = '{$last_info['id']}'");
				$tocode = new \Go\Util\tocode();
				$tocode->shop = $shop;
				$tocode->run_tocode($time,100,$shop['canyurenshu'],$shop);
				$content = addslashes($tocode->go_content);
			}
		}
	}
	/////////////////

	$u_go_info = $db->query("select * from `__PREFIX__member_go_record` where `shopid` = '$shop[id]' and `shopqishu` = '$shop[qishu]' and `goucode` LIKE  '%$code%'");
	$u_go_info = current($u_go_info);
	$u_info = $db->query("select userId,userName,userEmail,userPhone,userPhoto from `__PREFIX__users` where `userId` = '$u_go_info[uid]'");
	$u_info = current($u_info);
	//更新商品
	$query = true;
	if($u_info){
		$u_info['username'] = _htmtocode($u_info['userName']);
		$q_user = serialize($u_info);
		$gtimes = (int)C('GOODS_END_TIME');
		if($gtimes == 0 || $gtimes == 1){
			$q_showtime = 'N';
		}else{
			$q_showtime = 'Y';
		}
		$sqlss = "UPDATE `__PREFIX__shoplist` SET
		`canyurenshu`=`zongrenshu`,
		`shenyurenshu` = '0',
		`q_uid` = '$u_info[userId]',
		`q_user` = '$q_user',
		`q_user_code` = '$code',
		`q_content`	= '$content',
		`q_counttime` ='$counttime',
		`q_end_time` = '$time',
		`opencode` = '{$time_time_data['opencode']}',
		`opentime` = '{$time_time_data['opentime']}',
				`q_showtime` = '$q_showtime'
				where `id` = '$shop[id]'";


				file_put_contents("asasas.sql",$sqlss);

						$q = $db->execute($sqlss);

						if(!$q)$query = false;

						if($q){
						$q = $db->execute("UPDATE `__PREFIX__member_go_record` SET `huode` = '$code' where `id` = '$u_go_info[id]' and `code` = '$u_go_info[code]' and `uid` = '$u_go_info[uid]' and `shopid` = '$shop[id]' and `shopqishu` = '$shop[qishu]'");
						if(!$q) {
							$query = false;
						}else{
							$post_arr= array("uid"=>$u_info['userId'],"gid"=>$shop['id'],"send"=>1);
							_socket(HTTP.HTTP_HOST.U('Send/send_shop_code'),false,$post_arr);
						}
	}else{
		$query =  false;
	}
}else{
	$query =  false;
}

	/******************************/
	/*新建*/
	if($query){
		if($shop['qishu'] < $shop['maxqishu']){
			$maxinfo = $db->query("select * from `__PREFIX__shoplist` where `sid` = '$shop[sid]' order by `qishu` DESC LIMIT 1");
			if(empty($maxinfo)){
				$maxinfo=array("qishu"=>$shop['qishu']);
			}else{
				$maxinfo = current($maxinfo);
			}
			$intall = content_add_shop_install($maxinfo,false);
			if(!$intall) return $query;
		}
	}
	return $query;
}


/**
 *	发送电子邮件
 *	@email 也可以是一个二维数组，包含邮件和用户名信息

function _sendemail($email,$username=null,$title='',$content='',$yes='',$no=''){
	$config = include_once ROOT_PATH.'/core/config/email.inc.php';
	if(!$username)$username="";
	if(!$yes)$yes="发送成功,如果没有收到，请到垃圾箱查看,\n请把".$config['fromName']."设置为信任,方便以后接收邮件";
	if(!$no)$no="发送失败，请重新点击发送";
	if(!_checkemail($email)){return false;}
	email::config($config);
	if(is_array($email)){
		email::adduser($email);
	}else{
		email::adduser($email,$username);
	}
	$if=email::send($title,$content);
	if($if){
		return $yes;
	}else{
		return $no;
	}
}
 **/

/**
 *	发送用户获奖邮箱
 *	email  		@用户邮箱地址
 *   uid    		@用户的ID
 *	usernname	@用户名称
 *	code  		@中奖号码
 *   shoptitle	@商品名称
 */

function send_email_code($email=null,$username=null,$uid=null,$code=null,$shoptitle=null){
	$model = new \Think\Model();
	$template = $model->query("select * from `__PREFIX__caches` where `key` = 'template_email_shop'");
	$config = system_config();
	$template = current($template);
	if(empty($template)){
		$template = array();
		$template['value'] =  "恭喜：{$username},你在". $config['mallName']."参与的{$shoptitle}已揭晓,揭晓结果是:".$code;
	}else{
		$template['value'] = str_ireplace("{用户名}",$username,$template['value']);
		$template['value'] = str_ireplace("{商品名称}",$shoptitle,$template['value']);
		$template['value'] = str_ireplace("{中奖码}",$code,$template['value']);
	}
	$title = "恭喜您!!! ";
	return WSTSendMail($email, $title, $template['value']);
}

/**
 *	发送用户手机获奖短信
 *	mobile @用户手机号
 *   uid    @用户的ID
 *	code   @中奖码
 */

function send_mobile_shop_code($mobile=null,$uid=null,$code=null){
	if(!$uid){
		return array('status' => 0,'msg' => '发送用户手机获奖短信,用户ID不能为空！');
	}
	if(!$mobile){
		return array('status' => 0,'msg' => '发送用户手机获奖短信,手机号码不能为空!');
	}
	if(!$code){
		return array('status' => 0,'msg' => '发送用户手机获奖短信,中奖码不能为空!');
	}
	$template = M('caches')->where(array('key' => 'template_mobile_shop'))->find();
	$config = system_config();
	if(!$template){
		$template = array();
		$content =  "你在".$config['mallName']."购买的商品已中奖,中奖码是:".$code.'【'.$config['smsSign'].'】';
	}
	if(empty($template['value'])){
		$content =  "你在".$config['mallName']."购买的商品已中奖,中奖码是:".$code.'【'.$config['smsSign'].'】';
	}else{
		if(strpos($template['value'],"00000000") == true){
			$content= str_ireplace("00000000",$code,$template['value']);
		}else{
			$content = $template['value'].$code;
		}
	}
	return WSTSendSMS($mobile,$content);
}

/**
 新建一期商品
info 	 商品的ID 或者 商品的数组
使用此函数注意传进来的的商品期数不等于最大期数
autocommit @是否开启事物
*/
function content_add_shop_install($info=null,$autocommit=true){
	$db = new \Think\Model();
	if($autocommit){
		$db->startTrans();
	}

	unset($info['id']);
	unset($info['q_uid']);
	unset($info['q_user']);
	unset($info['q_user_code']);
	unset($info['q_content']);
	unset($info['q_counttime']);
	unset($info['q_end_time']);
	unset($info['opentime']);
	unset($info['opencode']);

	$info['xsjx_time']=0;
	$info['time'] = time();
	$info['qishu'] = intval($info['qishu']);
	$info['qishu']++;
	$info['canyurenshu'] = '0';
	$info['shenyurenshu'] = $info['zongrenshu'];
	$info['codes_table'] = content_get_codes_table();
	$info['q_showtime']= 'N';
	$info['title'] = _htmtocode($info['title']);
	$info['title2'] = _htmtocode($info['title2']);

	$keys  = $vals = '(';
	foreach($info as $key=>$val){
		$keys.="`$key`,";
		$vals.="'$val',";
	}
	$keys = rtrim($keys,',');
	$vals = rtrim($vals,',');
	$keys.= ')';
	$vals.= ')';

	$sql = "INSERT INTO `__PREFIX__shoplist` ".$keys." VALUES ".$vals;
	$q1 = $db->execute($sql);
	$id = $db->getLastInsID();
	$q2 = content_get_go_codes($info['zongrenshu'],3000,$id);

	if($autocommit){
		if($q1 && $q2){
			$db->commit();
			return true;
		}else{
			$db->rollback();
			return false;
		}
	}else{
		if($q1 && $q2){
			return true;
		}else{
			return false;
		}
	}

}

/* 网络操作函数 */
function _socket($url,$io=false,$post_data = array(), $cookie = array()){
	//ignore_user_abort(true);
	//set_time_limit(0);
	$method = empty($post_data) ? 'GET' : 'POST';

	$url_array = parse_url($url);
	$port = isset($url_array['port'])? $url_array['port'] : 80;

	if(function_exists('fsockopen')){
		$fp = @fsockopen($url_array['host'], $port, $errno, $errstr, 30);
	}elseif(function_exists('pfsockopen')){
		$fp = @pfsockopen($url_array['host'], $port, $errno, $errstr, 30);
	}elseif(function_exists('stream_socket_client')){
		$fp = @stream_socket_client($url_array['host'].':'.$port,$errno,$errstr,30);
	} else {
		$fp = false;
	}

	if(!$fp){
		return false;
	}

	$url_array['query'] =  isset($url_array['query']) ? $url_array['query'] : '';
	$getPath = $url_array['path'] ."?". $url_array['query'];

	$header  = $method . " " . $getPath." ";
	$header .= "HTTP/1.1\r\n";
	$header .= "Host: ".$url_array['host']."\r\n"; //HTTP 1.1 Host域不能省略
	$header .= "Pragma: no-cache\r\n";

	/*
	 //以下头信息域可以省略
	$header .= "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13 \r\n";
	$header .= "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,q=0.5 \r\n";
	$header .= "Accept-Language: en-us,en;q=0.5 ";
	$header .= "Accept-Encoding: gzip,deflate\r\n";
	*/

	if(!empty($cookie)){
		$_cookie_s = strval(NULL);
		foreach($cookie as $k => $v){
			$_cookie_s .= $k."=".$v."; ";
		}
		$_cookie_s = rtrim($_cookie_s,"; ");
		$cookie_str =  "Cookie: " . base64_encode($_cookie_s) ." \r\n";	   //传递Cookie
		$header .= $cookie_str;
	}
	$post_str = '';
	if(!empty($post_data)){
		$_post = strval(NULL);
		foreach($post_data as $k => $v){
			$_post .= $k."=".urlencode($v)."&";
		}
		$_post = rtrim($_post,"&");
		$header .= "Content-Type: application/x-www-form-urlencoded\r\n";//POST数据
		$header .= "Content-Length: ". strlen($_post) ." \r\n";//POST数据的长度

		$post_str = $_post."\r\n"; //传递POST数据
	}
	$header .= "Connection: Close\r\n\r\n";
	$header .= $post_str;

	fwrite($fp,$header);
	if($io){
		while (!feof($fp)){
			echo fgets($fp,1024);
		}
	}
	fclose($fp);
	//echo $header;
	return true;
}
